/**
 * @Date 2023-02-03 16:18:28
 * @Remark
 */

// react
import React, { useEffect, useState } from "react";
// lib
import { Button } from "antd";
// config
import { VERIFY_CODE } from "config/setting";
import { isMobile } from "utils/validator";
import toast from "./toast";
// public
// import logUtils from "utils/logUtils";
// service
import { getUserCodeService } from "biz/User/service";
// 其它

function CodeBtn(props: { mobile: () => string }) {
  const { mobile } = props;

  const [timer, setTimer] = useState<any>(0);
  const [count, setCount] = useState(VERIFY_CODE.INTERVAL_TIME);

  const flag = count !== VERIFY_CODE.INTERVAL_TIME;
  // 获得验证码
  async function getVerifyCode() {
    const _mobile = mobile();
    if (_mobile === "" || !isMobile(_mobile)) {
      toast.warning("手机号码格式错误");
      return;
    }
    setTimerAction();
    const result = await getUserCodeService(_mobile);
    if (result.payload) {
      toast.success("验证码已经发送");
    }
  }

  function changeCount(num: number) {
    if (num >= 0) {
      setCount(num);
    }
  }

  function setTimerAction() {
    // 倒计时
    let mCount = VERIFY_CODE.INTERVAL_TIME;
    mCount -= 1;
    changeCount(mCount);
    const timerContainer = setInterval(() => {
      mCount -= 1;
      changeCount(mCount);
    }, 1000);
    setTimer(timerContainer);
  }

  useEffect(() => {
    if (count === 0 && timer) {
      clearInterval(timer);
      setTimer(0);
      setCount(VERIFY_CODE.INTERVAL_TIME);
    }
  }, [count, timer]);

  useEffect(() => {
    //
    return () => {
      if (timer) {
        clearInterval(timer);
        setTimer(0);
      }
    };
  }, [timer]);

  return (
    <Button type="primary" disabled={flag} onClick={getVerifyCode}>
      {flag ? `${count}S` : "获得验证码"}
    </Button>
  );
}

export default CodeBtn;
